package com.question.business.dict.repository.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.question.business.dict.model.dto.DictCacheDTO;
import com.question.business.dict.repository.IDictCacheRepository;
import com.question.business.dict.service.IDictTypeService;
import com.question.common.constants.RedisConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典缓存Repository实现类
 *
 * @author star
 * @since 2023/9/7
 */
@Slf4j
@Service
@AllArgsConstructor
public class DictCacheRepositoryImpl implements IDictCacheRepository {

    private IDictTypeService dictTypeService;

    private RedisTemplate redisTemplate;

    /**
     * 根据字典类型查询缓存
     *
     * @param dictType 字典类型
     * @return List<DictCacheDTO>
     */
    @Override
    public List<DictCacheDTO> queryByType(String dictType) {
        HashOperations<String, String, List<DictCacheDTO>> ops = redisTemplate.opsForHash();
        return ops.get(RedisConstants.DICT_CACHE, dictType);
    }

    /**
     * 根据字典类型查询缓存
     *
     * @param dictType 字典类型
     * @return Map<String, DictCacheDTO>
     */
    @Override
    public Map<String, DictCacheDTO> queryMapByType(String dictType) {
        HashOperations<String, String, List<DictCacheDTO>> ops = redisTemplate.opsForHash();
        List<DictCacheDTO> list = ops.get(RedisConstants.DICT_CACHE, dictType);
        return CollectionUtils.isEmpty(list) ? null : list.stream().collect(Collectors.toMap(DictCacheDTO::getDictCode, dto -> dto));
    }

    /**
     * 字典缓存初始化
     */
    @Override
    public void initCache() {
        log.info("字典缓存初始化开始");
        List<DictCacheDTO> list = dictTypeService.queryDictCache();
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, List<DictCacheDTO>> map = list.stream().collect(Collectors.groupingBy(DictCacheDTO::getDictType));
            HashOperations<String, String, List<DictCacheDTO>> ops = redisTemplate.opsForHash();
            ops.putAll(RedisConstants.DICT_CACHE, map);
        }
        log.info("字典缓存初始化结束");
    }

}
